package com.qingfeng.medical.job.sys;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.qingfeng.medical.base.handler.GeneralAuthException;
import com.qingfeng.medical.biz.auth.dao.SysUserMapper;
import com.qingfeng.medical.biz.auth.dao.SysUserRoleMapper;
import com.qingfeng.medical.biz.auth.domain.entity.SysUser;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 系统信息管理
 *
 * @author 清风学Java
 * @version 1.0.0
 * @date 2023/4/8
 */
@Component
@Slf4j
public class SystemInformationManagementHandler {

    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    /**
     * 清理数据库中已删除的用户数据
     *
     * @return
     */
    @Transactional(rollbackFor = GeneralAuthException.class)
    @XxlJob(value = "clean-up-abandoned-user-data")
    public ReturnT cleanUpAbandonedUserData() {
        List<SysUser> sysUsers = sysUserMapper.selectList(
                new LambdaQueryWrapper<SysUser>()
                        .eq(SysUser::getIsDeleted, 1)
        );

        if (CollUtil.isNotEmpty(sysUsers)) {
            // 清理已经删除的用户数据
            sysUserMapper.deleteUser();

            // 用户数据被清理后，清理关联的角色信息
            sysUserRoleMapper.deleteUserRole(
                    sysUsers.stream()
                            .map(SysUser::getId)
                            .collect(Collectors.toList())
            );
        }
        return ReturnT.SUCCESS;
    }
}
